import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.views import View
from django.http import JsonResponse, HttpResponse
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from Model.models import Client, District, Subdistrict, Address, Community
from tools.Tools import getCurrentUser, createHandleLog, createFile, getFileBytes

res = dict()
logger_info = logging.getLogger('info')


class ClientView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        try:
            current = request.GET.get("current")
            pageSize = request.GET.get("pageSize")
            name = request.GET.get("name")
            telephone = request.GET.get("telephone")
            install_address = request.GET.get("install_address")
            dataInfo = Client.objects.all().order_by('-id')
            if name is not None and name != '':
                dataInfo = dataInfo.filter(name__contains=name)
            if telephone is not None and telephone != '':
                dataInfo = dataInfo.filter(telephone__contains=telephone)
            if install_address is not None and install_address != '':
                dataInfo = dataInfo.filter(install_address__contains=install_address)
            total = dataInfo.__len__()
            data = list(dataInfo.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
            res['status'] = 200
            res['data'] = data
            res['total'] = total
            res['current'] = current
            res['pageSize'] = pageSize
            res['messages'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            name = request.POST.get('name')
            telephone = request.POST.get('telephone')
            district = request.POST.get('district')
            subdistrict = request.POST.get('subdistrict')
            community = request.POST.get('community')
            address = request.POST.get('address')
            detail_address = request.POST.get('detail_address')
            certificate_type = request.POST.get('certificate_type')
            certificate = request.POST.get('certificate')
            img = request.FILES.get('img')
            if not Client.objects.filter(name=name, telephone=telephone).exists():
                createDate = Client.objects.create()
                file_path = createFile(createDate.id, img, '身份证')
                createDate.client_id = createDate.id
                createDate.name = name
                createDate.telephone = telephone
                createDate.district = district
                createDate.subdistrict = subdistrict
                createDate.community = community
                createDate.address = address
                createDate.detail_address = detail_address
                district_name = District.objects.get(district_id=district).name
                subdistrict_name = Subdistrict.objects.get(subdistrict_id=subdistrict).name
                community_name = Community.objects.get(community_id=community).name
                address_name = Address.objects.get(address_id=address).name
                createDate.install_address = district_name + subdistrict_name + community_name + address_name + detail_address
                createDate.certificate_type = certificate_type
                createDate.certificate = certificate
                createDate.certificate_img = file_path
                createDate.create_date = datetime.now()
                createDate.operator = getCurrentUser(request)
                createDate.save()
                res['status'] = 200
                res['message'] = '客户添加成功'
                createHandleLog('新增客户', str(getCurrentUser(request)), name)
                logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增客户》权限 新增内容 {name}')
            else:
                res['status'] = 400
                res['message'] = '不能添加已有客户'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def put(self, request, *args, **kwargs):
        print("PUT-请求")
        try:
            body = json.loads(request.body)
            client_id = body.get('client_id')
            name = body.get('name')
            telephone = body.get('telephone')
            district = body.get('district')
            subdistrict = body.get('subdistrict')
            community = body.get('community')
            address = body.get('address')
            detail_address = body.get('detail_address')
            modifyData = Client.objects.get(client_id=client_id)
            modifyData.name = name
            modifyData.telephone = telephone
            modifyData.district = district
            modifyData.subdistrict = subdistrict
            modifyData.community = community
            modifyData.address = address
            modifyData.detail_address = detail_address
            district_name = District.objects.get(district_id=district).name
            subdistrict_name = Subdistrict.objects.get(subdistrict_id=subdistrict).name
            community_name = Community.objects.get(community_id=community).name
            address_name = Address.objects.get(address_id=address).name
            modifyData.install_address = district_name + subdistrict_name + community_name + address_name + detail_address
            modifyData.save()
            res['status'] = 200
            res['message'] = '用户修改成功'
            createHandleLog('修改客户', str(getCurrentUser(request)), body)
            logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改客户》权限 修改内容 {body}')
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 200
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        try:
            clientID = request.GET.get("clientId")
            delClient = Client.objects.get(client_id=clientID)
            delClient.delete()
            res['status'] = 200
            res['message'] = '客户删除成功'
            createHandleLog('删除客户', str(getCurrentUser(request)), delClient.name)
            logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除客户》权限 删除内容 {delClient.name}')
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 200
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def downloadClientExample(request):
    res.clear()
    try:
        out_stream = getFileBytes('客户下载样例.xls')
        response = HttpResponse(content_type='application/vnd.ms-excel', charset="UTF-8")
        response.write(out_stream)
        return response
    except Exception as e:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)
